function bsdata=block_bootstrap(data,w,B)
% PURPOSE:
%   Implements a moving and overlapping block bootstrapping
%   for stationary and dependent series 
% 
% USAGE:
%     [bsdata, indexes]=block_bootstrap(data,w,B);
% 
% INPUTS:
%     data: t by k matrix of data to be bootstrapped. t is the lenght of
%     the time series and k is the number of variables.
%     w:    Desired average windows length
%     B:    Number fo bootstraps
% 
% OUTPUTS:
%     bsdata: t x k x B matrix of bootstrapped data
%     indexes: t by B matrix of location of the original data;
% 
% COMMENTS:
% 
% Author: Kevin Sheppard and changed by Martin M. Andreasen
% The original codes for [bsdata, indexes]=block_bootstrap(data,w,B)
%[t,k]=size(data);
%data=[data;data(1:w)];
%s=ceil(t/w);
%Bs=rand(s,B);
%indexes=zeros(t,B);
%index=1;
%for i=1:t
%    if mod(i,w)==1
%        indexes(i,:)=ceil(Bs(index,:)*t);
%        index=index+1;    
%    else
%        indexes(i,:)=indexes(i-1,:)+1;
%    end
%end
%indexes
%max(indexes(:,:))
%bsdata=data(indexes);


% The number of observations in the historical data set
t=size(data,1);

% "Extending" the historical data set such that starting a block at time
% t-2 does not lead to a break if w > 2
data=[data;data(1:w,:)];

% The lenght of the blocks
s=ceil(t/w);

% The indexes for the Blocks
Bs=rand(s,B);
indexes=zeros(t,B);
index=1;
for i=1:t
    if mod(i,w)==1  %The random starting point for the block in the data
        indexes(i,:)=ceil(Bs(index,:)*t);
        index=index+1;    
    else
        indexes(i,:)=indexes(i-1,:)+1;
    end
end

% The bootstrapped data is constructed from blocks and calculating the test
% statistic
bsdata = zeros(t,size(data,2),B);
for b=1:B;
    bsdata(:,:,b)=data(indexes(:,b),:);
end

